package com.rzx.mybackend.service.Impl;

import com.rzx.mybackend.entity.RabbitMQLog;
import com.rzx.mybackend.mapper.RabbitMQMapper;
import com.rzx.mybackend.service.RabbitMQService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

/**
 * RabbitMQServiceImpl
 *
 * @author renzhexian
 * @date 2025/7/24
 */
@Service
@RequiredArgsConstructor
public class RabbitMQServiceImpl implements RabbitMQService {

    private static final Logger log = LoggerFactory.getLogger(RabbitMQServiceImpl.class);
    private final RabbitMQMapper rabbitMQMapper;

    private final RabbitTemplate rabbitTemplate;

    /*
    记录RabbitMQ消息日志
     */
    @Override
    public void logComment(RabbitMQLog rabbitMQLog) {
        rabbitMQMapper.logComment(rabbitMQLog);
    }

    /*
    根据消息ID获取RabbitMQ日志信息
     */
    @Override
    public RabbitMQLog getInfoById(String msgId) {

        return rabbitMQMapper.getInfoById(msgId);
    }

    /*
    重试发送消息
    Spring Retryable 注解用于重试。
     */
    @Retryable(
            value = {Exception.class},              // 需要重试的异常类型
            maxAttempts = 1,                        // 最大尝试次数（1次原始调用 + 3次重试）
            backoff = @Backoff(
                    delay = 1000,                       // 初始延迟1秒
                    multiplier = 2,                     // 延迟倍数（指数退避）
                    maxDelay = 10000                    // 最大延迟10秒
            )
    )
    public void reytryMessage(String msgId) {
        // 获取失败消息
        RabbitMQLog rabbitMQLog = this.getInfoById(msgId);

        log.info("重试发送消息，ID: {}, 内容: {}", msgId, rabbitMQLog.getMsgContent());

        rabbitTemplate.convertAndSend(rabbitMQLog.getMqExchange(), rabbitMQLog.getMqRoute(), rabbitMQLog.getMsgContent());
    }
}
